import { request, uploadFile, uploadFiles } from './index'
import { BaseApiService, BaseUploadService, ApiResponseHandler, ApiCache } from './base'
import type { 
  ImageModel, 
  PaginatedResponse, 
  ApiResponse,
  SearchCriteria
} from '@/types'

// 上传图片
export const uploadImage = (
  formData: FormData, 
  onProgress?: (progressEvent: any) => void
): Promise<ApiResponse<ImageModel>> => {
  return uploadFile('/upload/single', formData.get('file') as File, (progress) => {
    if (onProgress) {
      onProgress({ loaded: progress, total: 100 })
    }
  })
}

// 根据ID获取图片
export const getImageById = (id: number): Promise<ApiResponse<ImageModel>> => {
  return request.get(`/images/${id}`)
}

// 图片API服务类
class ImageApiService extends BaseApiService<ImageModel> {
  constructor() {
    super('/images')
  }

  // 获取图片列表（带缓存）
  async getImages(params: {
    page?: number
    size?: number
    sortBy?: string
    sortDir?: string
  } = {}): Promise<PaginatedResponse<ImageModel>> {
    const cacheKey = ApiCache.generateKey(`${this.baseUrl}`, params)
    const cached = ApiCache.get<PaginatedResponse<ImageModel>>(cacheKey)
    
    if (cached) {
      return cached
    }

    const response = await request.get(this.baseUrl, { params })
    ApiCache.set(cacheKey, response, 2 * 60 * 1000) // 缓存2分钟
    return response
  }

  // 搜索图片
  async searchImages(params: {
    keyword: string
    page?: number
    size?: number
    sortBy?: string
    sortDir?: string
  }): Promise<PaginatedResponse<ImageModel>> {
    return request.get(`${this.baseUrl}/search`, { params })
  }

  // 高级搜索
  async advancedSearch(criteria: SearchCriteria): Promise<PaginatedResponse<ImageModel>> {
    return request.post(`${this.baseUrl}/advanced-search`, criteria)
  }

  // 根据标签筛选图片
  async getImagesByTag(tagName: string): Promise<ApiResponse<ImageModel[]>> {
    return request.get(`${this.baseUrl}/tag/${encodeURIComponent(tagName)}`)
  }

  // 根据多个标签筛选图片
  async getImagesByTags(tags: string[], logic: 'AND' | 'OR' = 'AND'): Promise<ApiResponse<ImageModel[]>> {
    return request.get(`${this.baseUrl}/tags`, { 
      params: { tags: tags.join(','), logic } 
    })
  }

  // 根据文件类型筛选图片
  async getImagesByMimeType(mimeType: string): Promise<ApiResponse<ImageModel[]>> {
    const encodedMimeType = mimeType.replace('/', '-')
    return request.get(`${this.baseUrl}/type/${encodedMimeType}`)
  }

  // 根据时间范围筛选图片
  async getImagesByDateRange(startTime: string, endTime: string): Promise<ApiResponse<ImageModel[]>> {
    return request.get(`${this.baseUrl}/date-range`, {
      params: { startTime, endTime }
    })
  }

  // 获取热门图片
  async getPopularImages(params: {
    page?: number
    size?: number
  } = {}): Promise<PaginatedResponse<ImageModel>> {
    return request.get(`${this.baseUrl}/popular`, { params })
  }

  // 按使用次数排序获取图片
  async getImagesSortedByUsage(params: {
    page?: number
    size?: number
    sortDir?: 'asc' | 'desc'
  } = {}): Promise<PaginatedResponse<ImageModel>> {
    return request.get(`${this.baseUrl}/sorted/usage`, { params })
  }

  // 按时间排序获取图片（默认按更新时间排序）
  async getImagesSortedByTime(params: {
    page?: number
    size?: number
    timeField?: 'updatedAt' | 'createdAt'
    sortDir?: 'asc' | 'desc'
  } = {}): Promise<PaginatedResponse<ImageModel>> {
    // 如果没有指定时间字段，默认使用更新时间
    const finalParams = {
      timeField: 'updatedAt',
      ...params
    }
    return request.get(`${this.baseUrl}/sorted/time`, { params: finalParams })
  }

  // 获取最近上传的图片
  async getRecentImages(limit: number = 10): Promise<ApiResponse<ImageModel[]>> {
    return request.get(`${this.baseUrl}/recent`, { params: { limit } })
  }

  // 更新图片信息
  async updateImage(id: number, data: Partial<ImageModel>): Promise<ApiResponse<ImageModel>> {
    const response = await request.put(`${this.baseUrl}/${id}`, data)
    // 清除相关缓存
    ApiCache.delete(ApiCache.generateKey(`${this.baseUrl}/${id}`))
    return response
  }

  // 删除图片
  async deleteImage(id: number): Promise<ApiResponse> {
    const response = await request.delete(`${this.baseUrl}/${id}`)
    // 清除相关缓存
    ApiCache.delete(ApiCache.generateKey(`${this.baseUrl}/${id}`))
    return response
  }

  // 批量删除图片
  async deleteImages(ids: number[]): Promise<ApiResponse> {
    const response = await request.post(`${this.baseUrl}/batch-delete`, { ids })
    // 清除相关缓存
    ids.forEach(id => {
      ApiCache.delete(ApiCache.generateKey(`${this.baseUrl}/${id}`))
    })
    return response
  }

  // 获取热门标签
  async getPopularTags(limit: number = 10): Promise<ApiResponse<Array<{
    tagName: string
    usageCount: number
  }>>> {
    const cacheKey = ApiCache.generateKey(`${this.baseUrl}/popular-tags`, { limit })
    const cached = ApiCache.get(cacheKey)
    
    if (cached) {
      return cached
    }

    const response = await request.get(`${this.baseUrl}/popular-tags`, { params: { limit } })
    ApiCache.set(cacheKey, response, 5 * 60 * 1000) // 缓存5分钟
    return response
  }

  // 获取图片统计信息
  async getImageStatistics(): Promise<ApiResponse> {
    const cacheKey = ApiCache.generateKey(`${this.baseUrl}/statistics`)
    const cached = ApiCache.get(cacheKey)
    
    if (cached) {
      return cached
    }

    const response = await request.get(`${this.baseUrl}/statistics`)
    ApiCache.set(cacheKey, response, 1 * 60 * 1000) // 缓存1分钟
    return response
  }
}

// 文件上传API服务类
class UploadApiService extends BaseUploadService {
  constructor() {
    super('/upload')
  }

  // 删除文件
  async deleteFile(imageId: number): Promise<ApiResponse> {
    return request.delete(`${this.baseUrl}/${imageId}`)
  }

  // 获取文件信息
  async getFileInfo(imageId: number): Promise<ApiResponse<ImageModel>> {
    return request.get(`${this.baseUrl}/info/${imageId}`)
  }

  // 获取上传统计信息
  async getUploadStatistics(): Promise<ApiResponse> {
    return request.get(`${this.baseUrl}/statistics`)
  }

  // 检查文件是否存在
  async checkFileExists(filePath: string): Promise<ApiResponse<{ exists: boolean }>> {
    return request.get(`${this.baseUrl}/exists`, { params: { filePath } })
  }

  // 获取上传进度
  async getUploadProgress(taskId: string): Promise<ApiResponse> {
    return request.get(`${this.baseUrl}/progress/${taskId}`)
  }
}

// 创建服务实例
export const imageApi = new ImageApiService()
export const uploadApi = new UploadApiService()